<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch" label-width="68px">
<!--      <el-form-item label="仓库编号" prop="storehouseNo">-->
<!--        <el-input-->
<!--          v-model="queryParams.storehouseNo"-->
<!--          placeholder="请输入仓库编号"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="仓库名称" prop="storehouseName">-->
<!--        <el-input-->
<!--          v-model="queryParams.storehouseName"-->
<!--          placeholder="请输入仓库名称"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="库区编号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入库区编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库区名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入库区名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="storehouseName">
        <el-input
          v-model="queryParams.storehouseName"
          placeholder="请输入仓库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="外部编号" prop="outerNo">-->
<!--        <el-input-->
<!--          v-model="queryParams.outerNo"-->
<!--          placeholder="请输入外部编号"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="排序" prop="sort">-->
<!--        <el-input-->
<!--          v-model="queryParams.sort"-->
<!--          placeholder="请输入排序"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basic:area:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basic:area:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basic:area:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['basic:area:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['basic:area:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="areaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="ID" align="center" prop="id" />-->
      <el-table-column label="库区编号" align="center" prop="no" min-width="100" show-overflow-tooltip="true"/>
      <el-table-column label="库区名称" align="center" prop="name" min-width="120" show-overflow-tooltip="true"/>
      <el-table-column label="仓库编号" align="center" prop="storehouseNo"  min-width="100" show-overflow-tooltip="true"/>
      <el-table-column label="仓库名称" align="center" prop="storehouseName"  min-width="100" show-overflow-tooltip="true"/>
      <el-table-column label="是否备料区" align="center" prop="whetherMp" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.whetherMp"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="状态" align="center" prop="status" />-->
<!--      <el-table-column label="外部编号" align="center" prop="outerNo" />-->
      <el-table-column label="码货员" align="center" prop="areaShipperStr" show-overflow-tooltip="true"/>
      <el-table-column label="拣货员" align="center" prop="areaPickerStr" show-overflow-tooltip="true"/>
      <el-table-column label="创建人" align="center" prop="createBy" min-width="100"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="155"/>
      <el-table-column label="最后更新人" align="center" prop="updateBy" min-width="100"/>
      <el-table-column label="最后更新时间" align="center" prop="updateTime" width="155"/>
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['system:area:edit']"-->
<!--          >修改</el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['system:area:remove']"-->
<!--          >删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库区对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="库区编号" prop="no">
          <el-input v-model="form.no" placeholder="请输入库区编号" :disabled="!!form.id"/>
        </el-form-item>
        <el-form-item label="库区名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入库区名称" />
        </el-form-item>
        <el-form-item label="仓库" prop="storehouseNo">
<!--          <el-input v-model="form.storehouseNo" placeholder="请选择仓库" />-->
          <el-select style="width:100%;" v-model="form.storehouseNo" filterable placeholder="请选择仓库">
            <el-option
              v-for="dict in storehouseList"
              :key="dict.no"
              :label="dict.name"
              :value="dict.no"
              @click.native="form.storehouseName = dict.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否备料区" prop="whetherMp">
          <el-select style="width:100%;" v-model="form.whetherMp" filterable placeholder="请选择备料区">
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="码货员" prop="areaShipperStr">
          <el-input @focus="openSelectUser" @change="clearShipper" v-model="form.areaShipperStr" placeholder="请选择码货员" clearable />
        </el-form-item>
        <el-form-item label="拣货员" prop="areaPickerStr">
          <el-input @focus="openSelectPickerUser" @change="clearPicker" v-model="form.areaPickerStr" placeholder="请选择拣货员" clearable />
        </el-form-item>

<!--        <el-form-item label="外部编号" prop="outerNo">-->
<!--          <el-input v-model="form.outerNo" placeholder="请输入外部编号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="备注" prop="remark">-->
<!--          <el-input v-model="form.remark" placeholder="请输入备注" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="排序" prop="sort">-->
<!--          <el-input v-model="form.sort" placeholder="请输入排序" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <select-user ref="select" @selectBack="selectBack" />

    <select-user ref="pickerSelect" @selectBack="selectPickerBack" />

  </div>
</template>

<script>
import { listArea, getArea, delArea, addArea, updateArea } from "@/api/basic/area";
import { listStorehouse } from "@/api/basic/storehouse";
import { getToken } from "@/utils/auth";
import selectUser from "./selectUser";

export default {
  name: "Area",
  components: { selectUser },
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      nos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库区表格数据
      areaList: [],
      //仓库列表
      storehouseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storehouseNo: null,
        storehouseName: null,
        no: null,
        name: null,
        status: null,
        outerNo: null,
        sort: null
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的物料数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basic/area/importExcel"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        storehouseNo: [
          { required: true, message: "仓库编不能为空", trigger: "change" }
        ],
        storehouseName: [
          { required: true, message: "仓库名称不能为空", trigger: "blur" }
        ],
        no: [
          { required: true, message: "库区编号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "库区名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        delFlag: [
          { required: true, message: "是否删除：1是 0否不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getStorehouseList();
  },
  methods: {
    clearShipper(){
      this.$set(this.form,'areaShipperList',[]);
    },
    clearPicker(){
      this.$set(this.form,'areaPickerList',[]);
    },
    /** 打开用户表弹窗 */
    openSelectUser() {
      this.$refs.select.show();
    },
    /** 打开拣货用户表弹窗 */
    openSelectPickerUser() {
      this.$refs.pickerSelect.show();
    },
    selectBack(userNames,nickNames){
      this.$set(this.form,'areaShipperStr',nickNames);
      // 组装数组对象
      let areaShipperList = [];
      let nickNameList = nickNames.split(",");
      userNames.split(",").forEach((item,index) => {
        areaShipperList.push({
          shipper:item,
          shipperName:nickNameList[index]
        });
      });
      this.$set(this.form,'areaShipperList',areaShipperList);
    },
    selectPickerBack(userNames,nickNames){
      this.$set(this.form,'areaPickerStr',nickNames);
      // 组装数组对象
      let areaShipperList = [];
      let nickNameList = nickNames.split(",");
      userNames.split(",").forEach((item,index) => {
        areaShipperList.push({
          shipper:item,
          shipperName:nickNameList[index]
        });
      });
      this.$set(this.form,'areaPickerList',areaShipperList);
    },
    /** 查询库区列表 */
    getList() {
      this.loading = true;
      listArea(this.queryParams).then(response => {
        this.areaList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storehouseNo: null,
        storehouseName: null,
        no: null,
        name: null,
        status: "0",
        outerNo: null,
        remark: null,
        delFlag: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        createTime: null,
        sort: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.nos = selection.map(item => item.no)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库区";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getArea(id).then(response => {
        this.form = response.data;
        if (this.form.areaShipperList && this.form.areaShipperList.length > 0){
          const names = this.form.areaShipperList.map(item => item.shipperName);
          this.$set(this.form,'areaShipperStr',names.join(','));
        }
        if (this.form.areaPickerList && this.form.areaPickerList.length > 0){
          const names = this.form.areaPickerList.map(item => item.shipperName);
          this.$set(this.form,'areaPickerStr',names.join(','));
        }
        this.open = true;
        this.title = "修改库区";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateArea(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArea(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const nos = row.no || this.nos;
      this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
        return delArea(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basic/area/export', {
        ...this.queryParams, ids: this.ids
      }, `库区管理_${new Date().getTime()}.xlsx`)
    },
    /** 获取仓库列表 */
    getStorehouseList(){
      listStorehouse().then(response => {
        this.storehouseList = response.rows;
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "库区导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('basic/area/importTemplate', {
      }, `库区模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
